// eslint-disable-next-line import/namespace
import { createProxyMiddleware } from 'http-proxy-middleware'
import bodyParser from 'koa-bodyparser'
// 文档 https://juejin.cn/post/7056425248513589262
import k2c from 'koa2-connect'
class Proxy {
  constructor(app) {
    this.app = app
  }

  // 代理程序
  intall(apiKey, apiUrl) {
    this.app.use(async (ctx, next) => {
      if (ctx.path.startsWith(`/${apiKey}`)) {
        // 匹配有api字段的请求url
        ctx.reponse = false // 绕过koa内置对象response ，写入原始res对象，而不是koa处理过的response
        // 需要 k2c 来链接
        await k2c(
          createProxyMiddleware(`/${apiKey}`, {
            target: apiUrl, // 目标链接
            changeOrigin: true, // needed for virtual hosted sites
            ws: true, // proxy websockets
            pathRewrite: {
              [`^/${apiKey}`]: '',
            },
          })
        )(ctx, next)
      }
      await next()
    })
    this.app.use(bodyParser()) // 跟这个没有啥关系
  }
}

export default Proxy
